<?php

	function escape( $string ) {
		if( ( get_magic_quotes_runtime() == 1 ) || ( get_magic_quotes_gpc() == 1 ) ) {
			$string = stripslashes( $string );
		}
		return mysql_real_escape_string( $string );
	}

	function getUserRolePower( $userRoleId ) {
		$userRole = getSingle( 'userRole', $userRoleId );
		return $userRole->getResultCount() > 0 ? $userRole->getPower() : 100;
	}

	function getYoutubeVideoId( $link ) {
		preg_match( "#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $link, $matches );
		return ( count( $matches ) > 0 ) ? $matches[ 0 ] : false;
	}
	
	function beautifyTrace( $array ) {
		$result = array();
		$arrlen = count( $array );
		foreach( $array as $i => $trace ) {
			$result[] = ( $arrlen - 1 - $i ) . ': ' . $trace[ 'file' ] . ' : ' . $trace[ 'line' ] . ' - ' . $trace[ 'function' ];
		}
		return implode( "\n", $result );
	}

	function getYoutubeVideoInfo( $id ) {
		$videoDetails = json_decode( @file_get_contents( 'http://gdata.youtube.com/feeds/api/videos/' . $id . '?alt=json' ), true );
		$videoInfo = array(
			'id' => $id,
			'title' => $videoDetails[ 'entry' ][ 'title' ][ '$t' ],
			'content' => $videoDetails[ 'entry' ][ 'content' ][ '$t' ],
			'category' => '',
			'keywords' => '',
			'author' => $videoDetails[ 'entry' ][ 'author' ][ 0 ][ 'name' ][ '$t' ],
			'handler' => end( explode( '/', $videoDetails[ 'entry' ][ 'author' ][ 0 ][ 'uri' ][ '$t' ] ) ),
			'url' => 'http://www.youtube.com/watch?v=' . $id,
			'channel' => 'http://www.youtube.com/user/' . end( explode( '/', $videoDetails[ 'entry' ][ 'author' ][ 0 ][ 'uri' ][ '$t' ] ) ),
			'duration' => $videoDetails[ 'entry' ][ 'media$group'][ 'yt$duration' ][ 'seconds' ],
			'comments' => $videoDetails[ 'entry' ][ 'gd$comments' ][ 'gd$feedLink' ][ 'countHint' ],
			'favourites' => $videoDetails[ 'entry' ][ 'yt$statistics' ][ 'favoriteCount' ],
			'views' => $videoDetails[ 'entry' ][ 'yt$statistics' ][ 'viewCount' ],
			'rating' => $videoDetails[ 'entry' ][ 'gd$rating' ][ 'average' ],
			'raters' => $videoDetails[ 'entry' ][ 'gd$rating' ][ 'numRaters' ]
		);
		$categories = array();
		if( isset( $videoDetails[ 'entry' ][ 'media$group'][ 'media$category' ] ) ){
			foreach( $videoDetails[ 'entry' ][ 'media$group'][ 'media$category' ] as $category ) {
				$categories[] = $category[ '$t' ];
			}
		}
		$videoInfo[ 'category' ] = implode( ', ', $categories );
		$keywords = array();
		if( isset( $videoDetails[ 'entry' ][ 'media$group'][ 'media$keywords' ] ) ){
			foreach( $videoDetails[ 'entry' ][ 'media$group'][ 'media$keywords' ] as $keyword ) {
				$keywords[] = $keyword[ '$t' ];
			}
		}
		$videoInfo[ 'keywords' ] = implode( ', ', $keywords );
		return $videoInfo;
	}

	function isHttps() {
		return $_SERVER[ 'SERVER_PORT' ] == 443 ? true : false;
	}

	function warnAdmin( $message ) {
		echo '<div style="background: #ffebe8;border: 1px solid #c00;margin: 10px 15px 10px 0;padding: 0 .6em;border-radius: 3px;-webkit-border-radius: 3px;-moz-border-radius: 3px;color: #c00;"><p style="margin: 1em 0;"><b>Warning :</b> ' . $message . '</p></div>';
	}

	function getOption( $option ) {
		try {
			return 'package';
			$options = getMultiple( 'option', array( 'optionName||' . $option ) );
			return $options->getResultCount() > 0 ? $options->getOptionValue() : '';
		} catch( Exception $ex ) {
			return 'default';
		}
	}

	function doInternaServerError( $html = false ) {
		$html = $html ? $html : '<div style="font-size:18px;line-height:1.6em;margin: 50px auto 40px auto;width: 600px;text-align: center;"><p><strong>Looks like something went wrong!</strong></p><p>We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing.</p></div>';
		header( 'HTTP/1.0 500 Internal Server Error', true );
		echo '<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>500 Internal Server Error</title></head><body>' . $html . '</body></htmL>';
	}

    function randomStringGenerator( $length, $small=false ) {
        $i = 0;
        $random_str = '';
        $a_to_z = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ123456789';
        $max = strlen($a_to_z) - 1;
        while ($i != $length) {
            $rand = mt_rand(0, $max);
            $random_str .= $a_to_z[$rand];
            $i++;
        }
        return $small ? strtolower($random_str) : $random_str;
    }

	function encrypt( $text, $key='zse' ) {
		return base64_encode( mcrypt_encrypt( MCRYPT_3DES, $key, base64_encode( $text ), MCRYPT_MODE_ECB ) );
	}

	function decrypt( $text, $key='zse' ) {    	
		return base64_decode( mcrypt_decrypt( MCRYPT_3DES, $key, base64_decode( $text ), MCRYPT_MODE_ECB ) );
	}

	function isValidEmailId( $emailId ) {
		//$pattern = "/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i";
		$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i'; //gmail + style email formats
		return preg_match( $pattern, $emailId ) > 0;
	}

	function isAjaxRequest() {
		return isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] );
	}

	function sanitizeWithDashes( $title, $preserveCase = false ) {
		$title = $preserveCase ? strip_tags( $title ) : strtolower( strip_tags( $title ) );
		foreach( array( '/&.+?;/', '/[^A-Za-z0-9 _-]/', '/\s+/', '|-+|' ) as $regex ) {
			$title = preg_replace( $regex, '-', $title );
		}
		return trim( $title, '-' );
	}

	function camelToUnderScore( $string ) {
		$newStr = '';
		for( $i = 0; $i < strlen( $string ); $i++ ) {
			$char = substr( $string, $i, 1 );
			if( strtolower( $char ) != $char ) {
				$newStr .= '_' . strtolower( $char );
			} else {
				$newStr .= $char;
			}
		}
		return $newStr;
	}

	function describe() {
		$arguments = func_get_args();
		if( count( $arguments ) == 0 ) {
			describe( 'Exit Call Handled . . .' );
			exit;
		}
		foreach( $arguments as $index => $thisVariable ) {
			if( $index == count( $arguments ) - 1 && count( $arguments ) != 1 && is_bool( $thisVariable ) ) {
				break;
			}
			if( is_string( $thisVariable ) ) {
				echo "\r\n<pre>" . $thisVariable . '</pre>';
			} else if( is_bool( $thisVariable ) ) {
				echo "\r\n<pre>";
				var_dump( $thisVariable );
				echo '</pre>';
			} else {
				echo "\r\n<pre>";
				print_r( $thisVariable );
				echo '</pre>';
			}
			flush();
		}
		if( $arguments[ count( $arguments ) - 1 ] === true && count( $arguments ) != 1 ) {
			describe( 'Exit Call Handled . . .' );
			exit;
		}
	}

	function getDb( $table, $task = 'show' ) {
		global $appDatabaseSettings;
		$table = explode( '_', $table, 2 );
		$classPrefix = ( count( $table ) == 2 ) ? $table[ 0 ] : $appDatabaseSettings[ 'default' ];
		$table = end( $table );
		$className = ucfirst( $classPrefix ) . '_Db_'. ucfirst( $table );
		if( !class_exists( $className ) ) {
			Loader::generateDbClass( $className );
		}
		return new $className( $task );
	}

	function getSingle( $table, $id ) {
		global $appDatabaseSettings;
		$table = explode( '_', $table, 2 );
		$classPrefix = ( count( $table ) == 2 ) ? $table[ 0 ] : $appDatabaseSettings[ 'default' ];
		$table = end( $table );
		$className = ucfirst( $classPrefix ) . '_' . ucfirst( $table );
		if( !class_exists( $className ) ) {
			Loader::generateSingularClass( $className );
		}
		return new $className( $id );
	}
	function getMultiple( $table, $filter = array() ) {
		global $appDatabaseSettings;
		$table = explode( '_', $table, 2 );
		$classPrefix = ( count( $table ) == 2 ) ? $table[ 0 ] : $appDatabaseSettings[ 'default' ];
		$table = end( $table );
		$className = ucfirst( $classPrefix ) . '_' . ucfirst( $table ) . 's';
		if( !class_exists( $className ) ) {
			Loader::generatePluralClass( $className );
		}
		if( is_string( $filter ) ) {
			$filter = func_get_args();
			unset( $filter[ 0 ] );
		}
		return new $className( $filter );
	}
	
	
	/*
	 * function to check the video run on witch plateform( e.g. mobile or desktop or pc etc )
	 */
	function check_user_agent ( $type = NULL ) {
		$user_agent = strtolower ( $_SERVER['HTTP_USER_AGENT'] );
		if ( $type == 'bot' ) {
			// matches popular bots
			if ( preg_match ( "/googlebot|adsbot|yahooseeker|yahoobot|msnbot|watchmouse|pingdom\.com|feedfetcher-google/", $user_agent ) ) {
				return true;
				// watchmouse|pingdom\.com are "uptime services"
			}
		} else if ( $type == 'browser' ) {
			// matches core browser types
			if ( preg_match ( "/mozilla\/|opera\//", $user_agent ) ) {
				return true;
			}
		} else if ( $type == 'mobile' ) {
			// matches popular mobile devices that have small screens and/or touch inputs
			// mobile devices have regional trends; some of these will have varying popularity in Europe, Asia, and America
			// detailed demographics are unknown, and South America, the Pacific Islands, and Africa trends might not be represented, here
			if ( preg_match ( "/phone|iphone|itouch|ipod|symbian|android|htc_|htc-|palmos|blackberry|opera mini|iemobile|windows ce|nokia|fennec|hiptop|kindle|mot |mot-|webos\/|samsung|sonyericsson|^sie-|nintendo/", $user_agent ) ) {
				// these are the most common
				return true;
			} else if ( preg_match ( "/mobile|pda;|avantgo|eudoraweb|minimo|netfront|brew|teleca|lg;|lge |wap;| wap /", $user_agent ) ) {
				// these are less common, and might not be worth checking
				return true;
			}
		}
		return false;
	}
	
	/*
	 * function to get video token url
	 */
	function getVideoTokenUrl( $videoMiddleUrlPart ){
		$url = "http://rnd11.vh1india.com/vod/stream/getToken.php";
		$json = file_get_contents($url);
		$token = json_decode($json, TRUE);
		
		/*return array(
			'sourcez' => "http://vodvh1in-vh.akamaihd.net/z/".$videoMiddleUrlPart."-2000000.mp4/manifest.f4m?hdnea=$token",
			'sourcei' => "http://vodvh1in-vh.akamaihd.net/i/".$videoMiddleUrlPart."-2000000.mp4/master.m3u8?hdnea=$token"
		);*/
		
		return array(
			'sourcez' => "http://vodsonicgangcom-vh.akamaihd.net/z/".$videoMiddleUrlPart."-2000000.mp4/manifest.f4m?hdnea=$token",
			'sourcei' => "http://vodsonicgangcom-vh.akamaihd.net/i/".$videoMiddleUrlPart."-2000000.mp4/master.m3u8?hdnea=$token"
		);

	}

    // Comparison function
	function cmp($a, $b) {
	    if ($a == $b) {
	        return 0;
	    }
	    return ($a > $b) ? -1 : 1;
	}
	
	function wpautop($pee, $br = 1) {
		$pee = $pee . "\n"; // just to make things a little easier, pad the end
		$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
		// Space things out a little
		$pee = preg_replace('!(<(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6])[^>]*>)!', "\n$1", $pee); 
		$pee = preg_replace('!(</(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6])>)!', "$1\n", $pee);
		$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines 
		$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
		$pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "\t<p>$1</p>\n", $pee); // make paragraphs, including one at the end 
		$pee = preg_replace('|<p>\s*?</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace 
	    $pee = preg_replace('!<p>\s*(</?(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|hr|pre|select|form|blockquote|address|math|p|h[1-6])[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
		$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
		$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
		$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
		$pee = preg_replace('!<p>\s*(</?(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|hr|pre|select|form|blockquote|address|math|p|h[1-6])[^>]*>)!', "$1", $pee);
		$pee = preg_replace('!(</?(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6])[^>]*>)\s*</p>!', "$1", $pee); 
		if ($br) $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
		$pee = preg_replace('!(</?(?:table|thead|tfoot|caption|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6])[^>]*>)\s*<br />!', "$1", $pee);
		$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)!', '$1', $pee);
		$pee = preg_replace('!(<pre.*?>)(.*?)</pre>!ise', " stripslashes('$1') .  clean_pre('$2')  . '</pre>' ", $pee);
		
		return $pee; 
	}
	
	function getGeoCountryCode(){
		require_once( dirname( __FILE__ ) . '/geoip/geoip.inc' );
		$gi = geoip_open( dirname( __FILE__ ) . '/geoip/GeoIP.dat', GEOIP_STANDARD);
		$countryCode = geoip_country_code_by_addr( $gi, getRealIpAddr() );
		geoip_close($gi);
		return $countryCode;
	}
	
	function getRealIpAddr() {
        if (!empty($_SERVER['HTTP_NS_REMOTE_ADDR'])) {  //
			$ip = $_SERVER['HTTP_NS_REMOTE_ADDR'];
        } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {  //check ip from share internet
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {   //to check ip is pass from proxy
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = @$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
    
    function getImageCustomFileName( $bannerMaxImgId ){
    	$objImg = getSingle( 'image', $bannerMaxImgId );
    	if( $objImg->getResultCount() > 0 ){
    		$imgArr = explode( "/", $objImg->getImageUri() );
    		$imgPart = $imgArr[ count( $imgArr ) - 1 ];
    		$imgFirstPart = explode( "_", $imgPart );
    		return $imgFirstPart[ 0 ];
    	}
    	return ImageUtility::randomStringGenerator( '10', true );
    		
    }


// timeAgo ( 2009-03-04 17:45 )
 function timeAgo($date)
	{
	    if(empty($date)) {
	        return "No date provided";
	    }
	    
	    $periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
	    $lengths         = array("60","60","24","7","4.35","12","10");
	    
	    $now             = time();
	    $unix_date         = strtotime($date);
	    
	       // check validity of date
	    if(empty($unix_date)) {    
	        return "Bad date";
	    }

	    // is it future date or past date
	    if($now > $unix_date) {    
	        $difference     = $now - $unix_date;
	        $tense         = "ago";
	        
	    } else {
	        $difference     = $unix_date - $now;
	        $tense         = "from now";
	    }
	    
	    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
	        $difference /= $lengths[$j];
	    }
	    
	    $difference = round($difference);
	    
	    if($difference != 1) {
	        $periods[$j].= "s";
	    }
	    
	    return "$difference $periods[$j] {$tense}";
	}
	
	function getTime($start_date, $end_date = null) {
		$time = array();
		
		if ($end_date === null) {
			$end_date = date('Y-m-d h:i:s');
		}
		$post_duration = TimeDiff2($start_date, $end_date);
		if($post_duration)
		{
			$time['class'] = 'c-r';
		}
		else
		{
			$time['class'] = 'c-y';
			$post_duration = TimeDiff2($end_date, $start_date);
		}
		
		if ($post_duration < 1) {
			$show_duration = "few secs";
		} elseif ($post_duration < 60) {
			$show_duration = $post_duration . " m";
		} elseif($post_duration >= 60 && $post_duration < 48 * 60) {
			$post_duration1 = floor($post_duration / 60);
			$show_duration = $post_duration1 . " h";
		} else {
			$show_duration1 = (int) ($post_duration / (60 * 24));
			if ($show_duration1 == 1)
				$show_duration = $show_duration1 . " d";
			else
				$show_duration = $show_duration1 . " d";
		}
		$time['duration'] = $show_duration;
		
		return $time;
	}
	
	
	function timeDiff2($start_date, $end_date) {
		$end = strtotime($end_date);
		$start = strtotime($start_date);
	
		$difference = $end - $start;
		if ($difference > 0)
			$min = floor($difference / 60);
		else
			$min=0;
		return $min;
	}
	
	function getMonthDates( $monthDate )
	{
		$monthTotalDays = date('t', strtotime($monthDate));
		$currentMonth = date('m', strtotime($monthDate));
		$currentYear = date('Y', strtotime($monthDate));
	
		for( $d = 1; $d <= $monthTotalDays; $d++ )
		{
			$monthDate = date("Y-m-d", mktime(0, 0, 0, $currentMonth, $d, $currentYear));
			$monthDates[ $d ]['monthDate'] = $monthDate;
			$monthDates[ $d ]['weekDay'] = date('N', strtotime($monthDate));
		}
		return $monthDates;
	}
	
	function add_date($givendate, $day=0, $mth=0, $yr=0) {
		$cd = strtotime($givendate);
	
		$newdate = date('Y-m-d', mktime(date('h', $cd), date('i', $cd), date('s', $cd), date('m', $cd) + $mth, date('d', $cd) + $day, date('Y', $cd) + $yr));
	
		return $newdate;
	}
	
	function getWeekDates( $weekDate )
	{
		$currentWeekDate = date('N', strtotime($weekDate));
		$startWeekDate = 1 - $currentWeekDate;
		$endWeekDate = 8 - $currentWeekDate;
		
		$currentDate = date('d', strtotime($weekDate));
		$currentMonth = date('m', strtotime($weekDate));
		$currentYear = date('Y', strtotime($weekDate));
	
		for( $d = $startWeekDate, $a=1; $d < $endWeekDate; $d++, $a++ )
		{
			$weekDates[ $a ] = date("Y-m-d", mktime(0, 0, 0, $currentMonth, $currentDate + $d, $currentYear));
		}
		return $weekDates;
	}
	
	function array_unique_recusive($arr){
		foreach($arr as $key=>$value)
			if(gettype($value)=='array')
			$arr[$key]=array_unique_recusive($value);
		return array_unique($arr,SORT_REGULAR);
	}
	
	function get_url_headers( $url ){
		$arrUrlHeaders = get_headers( $url );
	
		$urlHeaders = array();
		foreach( $arrUrlHeaders as $arrUrlHeader )
		{
			$temp = explode( ":", $arrUrlHeader);
			if( count( $temp ) == 2 )
			{
				$urlHeaders[ strtolower( $temp[0] ) ] = $temp[1];
			}
		}
		return $urlHeaders;
	}
	
	function sort_multi_array ($array, $key)
	{
		$keys = array();
		for ($i=1;$i<func_num_args();$i++) {
			$keys[$i-1] = func_get_arg($i);
		}
	
		// create a custom search function to pass to usort
		$func = function ($a, $b) use ($keys) {
			for ($i=0;$i<count($keys);$i++) {
				if ($a[$keys[$i]] != $b[$keys[$i]]) {
					return ($a[$keys[$i]] < $b[$keys[$i]]) ? -1 : 1;
				}
			}
			return 0;
		};
	
		usort($array, $func);
	
		return $array;
	}

    function getShortText( $text, $length )
    {
		if( strlen( $text ) > $length ){
			$position = strpos( $text, ' ', $length );
			if ( $position !== false && ( $position - $length ) < 10 ) {
				$text = substr( $text, 0, $position ) . '...';
			} else {
				$text = substr( $text, 0, $length ) . '...';
			}			
		}
		return $text;
    }

    function daysDifference( $startDate, $endDate ){
		$intervalObj = date_diff( date_create( $endDate ),  date_create( $startDate ) );
		return $intervalObj->format('%R%a');
    }
    
    function getDefaultUserImage( $gender, $dimension='' ){
    	return  '/images/defaultUserImg' . $dimension . strtolower($gender) . '.png';
    }
		
	function exportAsCsv( $array ){
		$csv = array(mysql_real_escape_string(implode(",", array_keys($array[0]))));
		foreach ($array as $a) {
			$csv[] = mysql_real_escape_string(implode(",", $a));
		}
		return implode("\n", $csv);
	}